/**
 * Created by Ysssssss on 2021/5/10.
 */


import React, { PureComponent } from 'react'
import {withRouter} from "react-router-dom";
import {connect} from "react-redux";

import {
    getProductDetailInfo,
    createProduct,
    editProduct,
} from "@sagas/productCenter";
import PageBackHeader from "@common/PageBackHeader";
import {Button, Form, Input, Row, Col} from "antd";
import {exchangeFormDataToFields} from "@utils/exchangeFormData";
import ProductDetailTypeSelect from "@components/productCenter/ProductDetailTypeSelect";
import {getHistoryMatchParams} from "@utils/setUrlQuery";
import ImageUpload from "@common/presentational/ImageUpload";
import ProductDetailProperty from "@components/productCenter/ProductDetailProperty";
import ProductDetailStandardHandle from "@components/productCenter/ProductDetailStandard";

const initProductInfo = {
    prod_type_id: '',
    name: '',
    unit: '',
    phonetic: '',
    title_pics: '',
    detail_pics: '',
    detail_description: '',
    skus: [],
    groups: [],
}

@connect(({ productCenter }) => ({
    productDetailMap: productCenter.productDetailMap,
}), {
    getProductDetailInfo,
    createProduct,
    editProduct,
})
@withRouter
class ProductDetailPage extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            productInfo: null,
            alreadySubmit: false
        }
        this.formRef = React.createRef()
    }

    componentDidMount () {
        const { productId } = getHistoryMatchParams(this.props)
        if (productId) {
            this.props.getProductDetailInfo({
                id: productId
            }, res => {
                this.setState({
                    productInfo: _.pick(res, Object.keys(initProductInfo)),
                })
            })
        } else {
            this.setState({
                productInfo: initProductInfo
            })
        }
        window.autoSetSkus = () => {
            this.setState({
                productInfo: {
                    ...this.state.productInfo,
                    skus: (this.state.productInfo.skus || []).map((sku,index) => ({
                        ...sku,
                        price: (index + 1) * 100,
                        weight: (index + 1) * 10
                    }))
                },
            })
        }
    }

    componentWillUnmount() {
        window.autoSetSkus = null
    }

    cancelEdit () {
        const { history } = this.props
        const { productNature } = getHistoryMatchParams(this.props)
        history.goBack(`/product-center/product/${productNature}/list`)
    }

    onFormItemChange (changedValues) {
        this.setState({
            productInfo: {
                ...this.state.productInfo,
                ...changedValues
            }
        })
    }

    handleSubmit () {
        this.formRef.current?.submit()
        this.setState({
            alreadySubmit: true
        })
    }

    submitForm (values) {
        const { productNature, productId } = getHistoryMatchParams(this.props)

        if (productId) {
            this.props.editProduct({
                id: productId,
                ...values,
            }, () => this.cancelEdit())
        } else {
            this.props.createProduct({
                productNature,
                ...values
            }, () => this.cancelEdit())
        }
    }

    validateSkuList (_, value) {
        const { productNature } = getHistoryMatchParams(this.props)
        return new Promise((resolve, reject) => {
            if (value.length > 200) {
                return reject(new Error(`商品最多支持200个规格`))
            }
            value.map(item => {
                let name = ''
                if (!item.price) {
                    name = item.items.map(sku => sku.item).join('，')
                    return reject(new Error(`${name}价格未填写`))
                }
                if (item.weight === '' && productNature !== 2) {
                    name = item.items.map(sku => sku.item).join('，')
                    return reject(new Error(`${name}重量未填写`))
                }
            })
            return resolve()
        });
    }

    validateTitlePics (_, value) {
        return new Promise((resolve, reject) => {
            if (value.length && value[0].includes('.mp4')) {
                return reject(new Error(`第一张必须为图片`))
            }
            return resolve()
        });
    }

    render () {
        const { productInfo, alreadySubmit } = this.state
        const { productId, productNature } = getHistoryMatchParams(this.props)

        return productInfo ? (
            <div className="bilin-web">
                <PageBackHeader title={productId ? '编辑商品' : '新建商品'} backUrl={`/product-center/product/${productNature}/list`}/>
                <div className="bilin-web-body form-page with-footer product-detail-page">
                    <Form
                        ref={this.formRef}
                        name="product-edit"
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        fields={exchangeFormDataToFields(productInfo)}
                        onValuesChange={this.onFormItemChange.bind(this)}
                        requiredMark={false}
                        onFinish={this.submitForm.bind(this)}
                        { ...(alreadySubmit ? {} : {
                            validateTrigger: "onSubmit"
                        }) }
                        scrollToFirstError={{
                            behavior: actions =>
                                actions.forEach(({ el, top, left }) => {
                                    el.scrollTop = top - 100
                                    el.scrollLeft = left
                                }),
                        }}
                    >
                        <div className="ft-16 pdt-36 pdb-36">基本信息</div>
                        <Form.Item
                            label='商品名称'
                            name='name'
                            rules={[
                                { required: true, message: '请输入名称' },
                            ]}
                        >
                            <Input placeholder="请输入名称" disabled={productId}/>
                        </Form.Item>
                        <Form.Item
                            label='商品类目'
                            name='prod_type_id'
                            rules={[
                                { required: true, message: '请选择商品类目' },
                            ]}
                        >
                            <ProductDetailTypeSelect productNature={productNature}/>
                        </Form.Item>
                        <Form.Item
                            label='商品单位'
                            name='unit'
                            rules={[
                                { required: true, message: '请输入商品单位' },
                            ]}
                        >
                            <Input placeholder="请输入商品单位"/>
                        </Form.Item>
                        <Row className="mgb-12">
                            <Col span={4}>商品主图</Col>
                            <Col span={20}>
                                <div className="ft-12 ft-clr-ml">图片格式：jpg, png, gif；单张图片不超过500kb</div>
                                <div className="ft-12 ft-clr-ml">视频格式: mp4；单个视频不超过5m</div>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={4} />
                            <Col span={20}>
                                <Form.Item
                                    name='title_pics'
                                    wrapperCol={{ span: 24 }}
                                    rules={[
                                        { validator: this.validateTitlePics.bind(this),}
                                    ]}
                                >
                                    <ImageUpload
                                        accept='image/png, image/jpeg, image/jpg, image/gif, video/mp4'
                                        uploadIntro=""
                                        maxLength={4}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={4}>商品描述</Col>
                            <Col span={20}>
                                <div className="bd-l">
                                    <Form.Item
                                        name='detail_description'
                                        className="mgb-12 no-bd"
                                        wrapperCol={{ span: 24 }}
                                    >
                                        <Input.TextArea
                                            placeholder="请输入商品描述"
                                            autoSize={{ minRows: 3, maxRows: 6 }}
                                            className="no-bd"
                                        />
                                    </Form.Item>
                                    <Form.Item
                                        name='detail_pics'
                                        className="mgb-0 pdl-8"
                                        wrapperCol={{ span: 24 }}
                                    >
                                        <ImageUpload
                                            uploadIntro=""
                                            maxLength={20}
                                        />
                                    </Form.Item>
                                </div>
                            </Col>
                        </Row>
                        <div className="ft-16 pdb-36">售价信息</div>
                        <Form.Item
                            name='groups'
                            label="添加规格"
                        >
                            <ProductDetailProperty productNature={productNature}/>
                        </Form.Item>
                        <Form.Item
                            name='skus'
                            wrapperCol={{ span: 24 }}
                            rules={[
                                { validator: this.validateSkuList.bind(this),}
                            ]}
                        >
                            <ProductDetailStandardHandle groups={productInfo.groups} productNature={productNature}/>
                        </Form.Item>
                    </Form>
                </div>
                <div className="bilin-web-footer">
                    <Button onClick={this.cancelEdit.bind(this)}>取消</Button>
                    <Button type="primary" onClick={this.handleSubmit.bind(this)}>保存</Button>
                </div>
            </div>
        ) : null
    }
}

export default ProductDetailPage